package ch14;

import javafoundations.*;

/**
 * Created by zhangyunqi on 2017/10/15.
 */
public abstract class ArrayStack<T> implements javafoundations.Stack <T>

{

    private final int DEFAULT_CAPACITY = 10;

    private int count;

    private T[] stack;

    public ArrayStack()

    {

        count = 0;

        stack = (T[]) (new Object[DEFAULT_CAPACITY]);

    }

    public T push(T element)

    {

        if (stack == null)
            throw new RuntimeException ( "插入的元素不可为NULL" );
        if (isFull ()) {
            enlarge ();

        }
        count++;
        // 往栈顶添加一个元素
        stack[count - 1] = element;
        return element;
    }


    public boolean isFull() {

        return stack.length == count;
    }

    public void enlarge() {
        T[] newData = (T[]) new Object[stack.length * 2];
        for (int i = 0; i < stack.length; i++) {
            newData[i] = stack[i];

        }
        stack = newData;

    }

    public T top() {
        if (isEmpty ()) {

            throw new RuntimeException ( "链表为空!!" );
        }
        return stack[count - 1];
    }


    private void expandCapacity()

    {

        T[] larger = (T[]) (new Object[stack.length * 3]);


        for (int index = 0; index < stack.length; index++)

            larger[index] = stack[index];

        stack = larger;

    }


    public T pop() throws EmptyCollectionException {

        if (isEmpty ())
            count--;
        T result = stack[count];
        stack[count] = null;
        return result;

    }

    public T peek() throws EmptyCollectionException

    {

        if (isEmpty ())

            return null;

        else

            return stack[count - 1];

    }


    public int size()

    {

        return count;

    }

    public boolean hasNext() {
        int a = -1;
        if (a < count - 1)
            return true;
        else
            return false;
    }

}
